package zhoug.zui.menu.tree;

import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import zhoug.common.adapters.recycler.BaseRecyclerViewAdapter;
import zhoug.common.adapters.recycler.BaseViewHolder;
import zhoug.logging.Logger;
import zhoug.zui.R;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

/**
 * 树形菜单
 *
 * @Author 35574
 * @Date 2020/11/20
 * @Description
 */
public class ZUITreeMenu extends LinearLayout {
    private static final String TAG = ">>>TreeMenu";
    private static final boolean DEBUG = false;

    private ColorStateList textColor;
    private float textSize;
    private ITreeNode select;//单选
    private List<ITreeNode> mSelected = new ArrayList<>();//多选
    private boolean multiSelectEnable = false;//是否启用多选

    /**
     * 同级菜单只能展开一个,展开时关闭其它
     */
    private boolean onlyExpandOne = true;

    protected int mCurrentExpandChangePosition = -1;//当前展开点击位置

    private RecyclerView mRecyclerView;
    private TreeMenuAdapter mTreeMenuAdapter;

    public ZUITreeMenu(Context context) {
        this(context, null);
    }

    public ZUITreeMenu(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, R.attr.ZUITreeMenu_theme);
    }

    public ZUITreeMenu(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mRecyclerView = (RecyclerView) LayoutInflater.from(context).inflate(R.layout.zui_tree_menu, this, false);
        addView(mRecyclerView);

        mRecyclerView.setLayoutManager(new LinearLayoutManager(context));
        mTreeMenuAdapter = new TreeMenuAdapter(context);
        mTreeMenuAdapter.setFirstMenu(true);
        mRecyclerView.setAdapter(mTreeMenuAdapter);

        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.ZUITreeMenu, defStyleAttr, R.style.ZUITreeMenu_def);
        textColor = a.getColorStateList(R.styleable.ZUITreeMenu_android_textColor);
        textSize = a.getDimension(R.styleable.ZUITreeMenu_android_textSize, 0);
        a.recycle();
    }

    public void setOnlyExpandOne(boolean onlyExpandOne) {
        this.onlyExpandOne = onlyExpandOne;
    }

    public void setMultiSelectEnable(boolean multiSelectEnable) {
        this.multiSelectEnable = multiSelectEnable;
    }

    /**
     * 设置节点数据
     *
     * @param treeNodes
     */
    public void setData(List<? extends ITreeNode> treeNodes) {
        mTreeMenuAdapter.setData(treeNodes);
        mTreeMenuAdapter.notifyDataSetChanged1();
    }

    /**
     * 刷新全部节点数据
     */
    public void notifyDataSetChanged() {
        mTreeMenuAdapter.notifyDataSetChanged1();
    }

    /**
     * 获取节点数据
     *
     * @return
     */
    public List<ITreeNode> getData() {
        return mTreeMenuAdapter.getData();
    }

    /**
     * 设置树形菜单监听
     *
     * @param onTreeMenuListener
     */
    public void setOnTreeMenuListener(OnTreeMenuListener onTreeMenuListener) {
        mTreeMenuAdapter.setOnTreeMenuListener(onTreeMenuListener);
    }

    /**
     * 设置选中
     *
     * @param treeNode
     */
    public void setSelect(ITreeNode treeNode) {
        this.select = treeNode;
    }


    /**
     * 是否选中
     *
     * @param itemData
     * @return
     */
    public boolean isSelected(ITreeNode itemData) {
        if (mSelected.size() > 0) {
            for (ITreeNode item : mSelected) {
                if (Objects.equals(item.getId(), itemData.getId())) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 移除选择
     *
     * @param itemData
     */
    public void remoteSelect(ITreeNode itemData) {
        mSelected.remove(itemData);
    }

    /**
     * 添加选中
     *
     * @param itemData
     */
    public void addSelected(ITreeNode itemData) {
        mSelected.add(itemData);
    }


    public List<ITreeNode> getSelected() {
        return mSelected;
    }

    public void setSelected(List<ITreeNode> selected) {
        this.mSelected.clear();
        if(selected!=null && selected.size()>0){
            this.mSelected.addAll(selected);
        }
    }

    /**
     * 节点数据适配器
     *
     * @Author 35574
     * @Date 2020/11/20
     * @Description
     */
    public class TreeMenuAdapter<T extends ITreeNode> extends BaseRecyclerViewAdapter<T> implements OnClickListener {
        private static final String TAG = ">>>TreeMenuAdapter";
        private boolean isFirstMenu;//是否是第一层菜单
        private ITreeNode lastExpandNode;//上次展开的节点
        private OnTreeMenuListener mOnTreeMenuListener;


        public TreeMenuAdapter(Context context) {
            super(context);
        }


        public void setOnTreeMenuListener(OnTreeMenuListener onTreeMenuListener) {
            this.mOnTreeMenuListener = onTreeMenuListener;
        }

        private boolean isFirstMenu() {
            return isFirstMenu;
        }

        private void setFirstMenu(boolean firstMenu) {
            isFirstMenu = firstMenu;
        }

        /**
         * 关闭全部子菜单
         *
         * @param node
         */
        private void closeAllChildMenu(ITreeNode node) {
            if (node != null) {
                List<? extends ITreeNode> children = node.getChild();
                if (children != null && children.size() > 0) {
                    for (ITreeNode child : children) {
                        if (child != null && child.isExpanded()) {
                            child.setExpanded(false);
                            closeAllChildMenu(child);
                        }
                    }
                }
            }
        }


        /**
         * 给定的节点是否展开
         *
         * @param node
         * @return
         */
        private boolean isExpanded(ITreeNode node) {
            return node != null && node.isExpanded();
        }

        /**
         * 关闭节点
         *
         * @param node
         * @return
         */
        public void closeExpanded(ITreeNode node) {
            if (node != null) {
                node.setExpanded(false);
                closeAllChildMenu(node);
            }
            notifyDataSetChanged1();
        }

        /**
         * 展开节点
         *
         * @param node
         * @return
         */
        public void openExpand(ITreeNode node) {
            //关闭上次展开的节点
            if (onlyExpandOne && lastExpandNode != null && lastExpandNode.isExpanded()) {
                lastExpandNode.setExpanded(false);
                closeAllChildMenu(lastExpandNode);
            }
            if (node != null) {
                node.setExpanded(true);
                lastExpandNode = node;
            }
            notifyDataSetChanged1();
        }


        @Override
        public int getLayoutId(int viewType) {
            return R.layout.zui_tree_menu_item;
        }

        @NonNull
        @Override
        public BaseViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            BaseViewHolder viewHolder = super.onCreateViewHolder(parent, viewType);
            TextView textView = viewHolder.getView(R.id.text_name);
            if (textColor != null) {
                textView.setTextColor(textColor);
            }
            if (textSize != 0) {
                textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize);
            }
            return viewHolder;
        }

        @Override
        public void onBindData(BaseViewHolder holder, ITreeNode data, int position, int viewType) {
            if (data != null) {
                if (DEBUG) {
                    Logger.d(TAG, "onBindData:" + data);
                }
//                ImageView imgLineTop = holder.getView(R.id.img_line_top);
//                ImageView imgLineCenter = holder.getView(R.id.img_line_center);
                ImageView imgExpand = holder.getView(R.id.img_expand);
                TextView textName = holder.getView(R.id.text_name);
                ImageView btnCheck = holder.getView(R.id.btn_check);
                RecyclerView childRecyclerView = holder.getView(R.id.zui_recyclerView_child);
                textName.setText(data.getName());

                //第一层的第一个不显示最上面的虚线
               /* if (isFirstMenu && position == 0) {
                    imgLineTop.setVisibility(INVISIBLE);
                } else {
                    imgLineTop.setVisibility(VISIBLE);
                }
                //每层菜单的最后一个数据,不显示下面的虚线
                if (position == getDataCount() - 1) {
                    imgLineCenter.setVisibility(GONE);
                } else {
                    imgLineCenter.setVisibility(VISIBLE);
                }*/

                if (multiSelectEnable) {
                    //多选
                    btnCheck.setVisibility(VISIBLE);
                    btnCheck.setSelected(isSelected(data));
                    btnCheck.setTag(position);
                    btnCheck.setClickable(true);
                    btnCheck.setOnClickListener(this);
                } else {
                    //单选
                    btnCheck.setVisibility(GONE);
                    if (select != null && select.equals(data)) {
                        textName.setSelected(true);
                    } else {
                        textName.setSelected(false);
                    }
                    textName.setClickable(true);
                    textName.setTag(position);
                    textName.setOnClickListener(this);
                }

                TreeMenuAdapter childAdapter = (TreeMenuAdapter) childRecyclerView.getAdapter();
                //展开状态
                if (isExpanded(data)) {
                    imgExpand.setImageResource(R.drawable.zui_tree_menu_expand_true);
                    //设置子节点
                    childRecyclerView.setVisibility(View.VISIBLE);
                    List<? extends ITreeNode> child = data.getChild();
                    if (childAdapter == null) {
                        childAdapter = new TreeMenuAdapter(getContext());
                        childRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
                        childAdapter.setOnTreeMenuListener(mOnTreeMenuListener);
                        childRecyclerView.setAdapter(childAdapter);
                    }
                    childAdapter.setData(child);
                    childAdapter.notifyDataSetChanged1();

                } else {
                    //关闭时需要关闭全部子菜单

                    childRecyclerView.setVisibility(View.GONE);
                    if (!data.isHasChild()) {
                        //没有子节点了
//                        imgExpand.setImageResource(R.drawable.zui_tree_menu_line_h);
                        imgExpand.setImageDrawable(null);
                    } else {
                        imgExpand.setImageResource(R.drawable.zui_tree_menu_expand_false);
                    }
                }

                if (data.isHasChild()) {
                    imgExpand.setClickable(true);
                    imgExpand.setTag(position);
                    imgExpand.setOnClickListener(this);
                } else {
                    imgExpand.setClickable(false);
                    imgExpand.setTag(position);
                }


            }
        }

        @Override
        public void onClick(View v) {
            int id = v.getId();
            int pos = (int) v.getTag();
            ITreeNode itemData = getItemData(pos);
            if (DEBUG) {
                Logger.d(TAG, "onClick:itemData=" + itemData);
            }
            if (id == R.id.img_expand) {
                if (isExpanded(itemData)) {
                    //展开->关闭
                    closeExpanded(itemData);
                    if (mOnTreeMenuListener != null) {
                        mOnTreeMenuListener.onExpand(TreeMenuAdapter.this, pos, itemData, false);
                    }
                } else {
                    //关闭->展开
                    List<? extends ITreeNode> child = itemData.getChild();
                    if (child != null && child.size() > 0) {
                        openExpand(itemData);
                        if (mOnTreeMenuListener != null) {
                            mOnTreeMenuListener.onExpand(TreeMenuAdapter.this, pos, itemData, true);
                        }
                    } else {
                        //没有child,那么先不要展开,
                        if (mOnTreeMenuListener != null) {
                            mOnTreeMenuListener.onExpandClick(TreeMenuAdapter.this, pos, itemData);
                        }
                    }
                }
                mCurrentExpandChangePosition = pos;
            } else if (id == R.id.text_name) {
                select = itemData;
                mTreeMenuAdapter.notifyDataSetChanged1();
                if (mOnTreeMenuListener != null) {
                    mOnTreeMenuListener.onSelect(TreeMenuAdapter.this, pos, itemData);
                }
            } else if (id == R.id.btn_check) {
                if (isSelected(itemData)) {
                    remoteSelect(itemData);
                } else {
                    addSelected(itemData);
                }
                mTreeMenuAdapter.notifyDataSetChanged1();
                if (mOnTreeMenuListener != null) {
                    mOnTreeMenuListener.onMultiSelectChange(TreeMenuAdapter.this, pos, mSelected, itemData);
                }
            }

        }

    }


    /**
     * 树形菜单监听器
     */
    public interface OnTreeMenuListener {
        /**
         * 选中监听
         *
         * @param treeNode
         */
        void onSelect(TreeMenuAdapter adapter, int position, ITreeNode treeNode);

        void onMultiSelectChange(TreeMenuAdapter adapter, int position, List<ITreeNode> selected, ITreeNode changeItem);

        /**
         * 展开/关闭状态监听
         *
         * @param treeNode
         * @param expand
         */
        void onExpand(TreeMenuAdapter adapter, int position, ITreeNode treeNode, boolean expand);

        /**
         * 点击意图展开但是{@link ITreeNode#getChild()}为空,用于动态加载child,
         * 需要先设置{@link ITreeNode#isHasChild()}为true才生效
         *
         * @param treeNode
         */
        void onExpandClick(TreeMenuAdapter adapter, int position, ITreeNode treeNode);

    }

}
